﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace NewsReader
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
            DataContext = App.CurrentNewsFeed;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            ApplicationBar = new ApplicationBar();
            ApplicationBar.IsMenuEnabled = true;
            ApplicationBar.IsVisible = true;
            ApplicationBar.Opacity = 1;
            ApplicationBarMenuItem settingsItem = new ApplicationBarMenuItem("settings");
            settingsItem.Click += new EventHandler(settingsItem_Click);
            ApplicationBar.MenuItems.Add(settingsItem);
        }

        void settingsItem_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.IsDataLoaded)
            {
                CategoriesListBox.SelectionChanged -= new SelectionChangedEventHandler(CategoriesListBox_SelectionChanged);
                App.CurrentNewsFeed.Refresh();
                CategoriesListBox.SelectionChanged += new SelectionChangedEventHandler(CategoriesListBox_SelectionChanged);
            }
        }

        private void CategoriesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CategoriesListBox.SelectedIndex == -1) return;
            NavigationService.Navigate(new Uri("/NewsCategory.xaml?selectedItem=" + ((KeyValuePair<string, string>)CategoriesListBox.SelectedItem).Key, UriKind.Relative));
            CategoriesListBox.SelectedIndex = -1;
        }
    }
}